<?php
// Copyright 2009 Oy Site Logic Ab
// 
// This file is part of a program, that is distributed
// under the terms of the GNU General Public License,
// see license.txt for details.

defined( '_JEXEC' ) or die( 'Restricted access' );

class pt_database extends JDatabaseMySQL {
	var $_global_db;
	
	public function __construct( $global_db ) {
		//global $mosConfig_host, $mosConfig_user, $mosConfig_password, $mosConfig_db, $mosConfig_dbprefix;
		
		$conf =& JFactory::getConfig();

		$host 		= $conf->getValue('config.host');
		$user 		= $conf->getValue('config.user');
		$password 	= $conf->getValue('config.password');
		$database	= $conf->getValue('config.db');
		$prefix 	= $conf->getValue('config.dbprefix');
		$driver 	= $conf->getValue('config.dbtype');
		$debug 		= $conf->getValue('config.debug');

		$options	= array ( 'driver' => $driver, 'host' => $host, 'user' => $user, 'password' => $password, 'database' => $database, 'prefix' => $prefix );
		
		parent::__construct($options);
		
		$this->_global_db = $global_db;
	}
	
	function replacePrefix( $sql, $prefix='#__' ) {
		global $palvelutiski_globalCats, $palvelutiski_siteGlobal;
		
		if ($palvelutiski_globalCats || $palvelutiski_siteGlobal) {
			$sql = str_replace('#__palvelutiski_categories', '@__palvelutiski_categories', $sql);
		}
		
		//Replace the default prefix;
		$sql = parent::replacePrefix($sql, $prefix);
		
		//Check if we need to replace our own prefix as well
		if (strpos($sql, '@__') !== FALSE) {
			//Save the normal table prefix
			$temp_prefix = $this->_table_prefix;
			
			//Set our own prefix and run the replacement again
			$this->_table_prefix = $this->_global_db;
			$sql = parent::replacePrefix($sql, '@__');
			
			//Restore the real table prefix
			$this->_table_prefix = $temp_prefix;
		}
		return $sql;
	}
}

//Create our own database
global $ptdb;
$ptdb = new pt_database($palvelutiski_globalTable);

?>